package com.example.nick.bodyapplication

import android.util.Log
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object TimerTick {
    var _sTime = 0L
    var _cancel = false
    var _delayTime = 2000
    var job: Job? = null

    fun delaySend(delayTime: Int) {
        if (_cancel) {
            return
        }
        _sTime = System.currentTimeMillis()
        _delayTime = delayTime
        Log.d("Flow", "Flow TimerTick delaySend 000 $this, sTime:$_sTime")
        if (job == null) {
            job = GlobalScope.launch {
                while (!_cancel) {
                    if (System.currentTimeMillis() - _sTime > _delayTime) {
                        Log.e("Flow", "Flow TimerTick delaySend, ${System.currentTimeMillis()}, sTime:$_sTime")
                        break
                    }
                    Log.i("Flow", "Flow TimerTick while")
                    delay(1000)
                }
            }
        }
        Log.d("Flow", "Flow TimerTick delaySend 111 $this, sTime:$_sTime")
    }

    fun enable() {
        _cancel = false
    }

    fun cancel() {
        _cancel = true
        job?.cancel()
    }
}